#include "mimetype.h"

using namespace core;

bool mimeTypeSortHelper(const QPair<QString, uint>& p1,
    const QPair<QString, uint>& p2)
{
    return p1.second < p2.second;
}

MimeType::MimeType() :
    m_isValid(false),
    m_name(),
    m_type(),
    m_icon(),
    m_comment(),
    m_globalPatterns(),
    m_suffixes(),
    m_actualGlobalPatterns()
{
}

MimeType::MimeType(const QString& name, const QString& type,
    const QString& icon, const GlobalPatternList& globalPatterns,
    const QString& comment) :
        m_isValid(true),
        m_name(name),
        m_type(type),
        m_icon(icon),
        m_comment(comment),
        m_globalPatterns(globalPatterns),
        m_suffixes(),
        m_actualGlobalPatterns()
{
    Q_ASSERT(!m_globalPatterns.isEmpty());

    qSort(m_globalPatterns.begin(), m_globalPatterns.end(),
        mimeTypeSortHelper);

    GlobalPatternList::const_iterator it = m_globalPatterns.constBegin();

    for (; it != m_globalPatterns.constEnd(); ++it)
    {
        QString _pattern = it->first;

        m_actualGlobalPatterns.append(_pattern);

        _pattern.remove("*.");
        m_suffixes.append(_pattern);
    }
}

QString MimeType::name() const
{
    return m_name;
}

QString MimeType::comment() const
{
    return m_comment;
}

QString MimeType::iconName() const
{
    return m_icon;
}

QString MimeType::filterString() const
{
    return globalPatterns().join(",");
}

QStringList MimeType::globalPatterns() const
{
    return m_actualGlobalPatterns;
}

QString MimeType::type() const
{
    return m_type;
}

QString MimeType::preferredSuffix() const
{
    return m_suffixes.last();
}

QStringList MimeType::suffixes() const
{
    return m_suffixes;
}

bool MimeType::isValid() const
{
    return m_isValid;
}

bool MimeType::operator==(const MimeType& other) const
{
    return m_name == other.m_name && m_type == other.m_type &&
        m_icon == other.m_icon && m_comment == m_comment &&
        m_globalPatterns == m_globalPatterns;
}

bool MimeType::operator!=(const MimeType& other) const
{
    return m_name != other.m_name || m_type != other.m_type ||
        m_icon != other.m_icon || m_comment != m_comment ||
        m_globalPatterns != m_globalPatterns;
}
